<template>
  <div>
    <el-button type="text" @click="showSelectBox">添加模型</el-button>
    <el-table
      v-if="checkModels.length > 0"
      :data="checkModels"
      class="code-detail-table"
      header-row-class-name="code-detail-table-header"
    >
      <el-table-column prop="model.name" label="名称" />
      <el-table-column prop="model_version.version" label="版本" />
      <el-table-column prop="model.alias" label="挂载地址" />
      <el-table-column prop="path" label="操作">
        <template slot-scope="{ row }">
          <!--<el-button type="text" @click="put(row)">修改</el-button>-->
          <el-button type="text" @click="removetag(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <DialogBox
      title="添加模型"
      width="50%"
      maxHeight="50vh"
      :appendToBody="true"
      :visible="showSelectDialog"
      :confirm="surebtn"
      :close="onClose"
    >
      <el-input
        placeholder="请输入内容"
        v-model="search"
        size="small"
        @keydown.enter="enter"
        @input="selectName"
        class="input-with-select"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>

      <!--      <el-tabs v-model="visibility" @tab-click="getModels">-->
      <!--        <el-tab-pane label="我的模型" name="0"></el-tab-pane>-->
      <!--        <el-tab-pane label="共享模型" name="1"></el-tab-pane>-->
      <!--      </el-tabs>-->
      <div class="radio_box">
        <el-radio-group v-model="visibility" @input="getModels">
          <el-radio-button :label="'0'" :name="'0'" :value="'0'"
            >我的模型</el-radio-button
          >
          <el-radio-button :label="'1'" :name="'1'" :value="'1'"
            >共享模型</el-radio-button
          >
        </el-radio-group>
      </div>

      <ul class="infinite-list clearfix">
        <li
          v-for="(item, index) in tableData"
          :key="index"
          class="infinite-list-item"
        >
          <el-checkbox
            v-model="item.checked"
            class="myself-dataset-checkbox"
            @change="currentSelect(item)"
          >
            <div class="">
              <v-image class="dimg" :src="item.avatar" />
              <div class="datas-box">
                <div class="pall-title">
                  <p class="pall datasname">
                    {{ item.name }}
                  </p>
                  <p class="pall-versions">
                    <span>版本</span>
                    <el-select
                      size="mini"
                      multiple
                      v-model="item.selectValue"
                      @change="handleVersionChange(item.selectValue, item)"
                    >
                      <el-option
                        v-for="version in item.versions"
                        :value="version.id"
                        :label="version.version"
                        :key="version.id"
                      >
                      </el-option>
                    </el-select>
                  </p>
                </div>
                <p class="pall pcontents" :title="item.desc">
                  {{ item.desc }}
                </p>
              </div>
            </div>
          </el-checkbox>
        </li>
      </ul>
      <div class="pagination-box" v-if="Pagedata.total > Pagedata.pageSize">
        <el-pagination
          background
          class="pagination"
          layout="total, prev, pager, next, jumper"
          :page-size="Pagedata.pageSize"
          :current-page.sync="Pagedata.pageNum"
          @current-change="handleCurrentChange"
          :total="Pagedata.total"
        >
        </el-pagination>
      </div>
    </DialogBox>
  </div>
</template>

<script>
import DialogBox from "@/components/module/dialog-box.vue";
import { getModelsWithVersion } from "@/api/model";
import { debounce } from "@/utils/tool";

export default {
  name: "plugInModel",
  data() {
    return {
      showSelectDialog: false,
      search: "",
      tableData: [],
      models: [],
      checkModels: [],
      visibility: "0",
      Pagedata: {
        pageNum: 1,
        pageSize: 5,
        total: 0,
        order: "create_time", // 排序recommend、createTime、likeCount
      },
      selectValue: [],
      showSelect: false,
      updatedDataList: null,
    };
  },
  props: ["model_list"],
  watch: {
    model_list(val) {
      console.log("val", val);
      this.checkModels = val;
    },
  },
  methods: {
    handleVersionChange(selectedIds, data) {
      console.log("Selecteddata", data);
      console.log("Selected", selectedIds);

      this.updatedDataList = data.selectValue.map((selectedId) => {
        // 对于每个 ID，过滤出对应的版本
        const filteredVersion = data.versions.filter(
          (version) => version.id == selectedId
        );
        console.log('filteredVersion',filteredVersion);
        const modelVersionUpdate = filteredVersion.length > 0 ? filteredVersion[0].version : null;
        const modelIdUpdate = filteredVersion.length > 0 ? filteredVersion[0].id : null;
        // 创建一个新的数据对象，包含过滤后的版本
        return {
          ...data, // 复制原始数据对象的所有属性
          versions: filteredVersion, // 但是只包含一个匹配的版本
          model_version_id:modelIdUpdate,
          model_version: {
            ...data.model_version,
            id:modelIdUpdate,
            version:modelVersionUpdate, // 更新版本或保持原版本
          },
        };
      });
      console.log('this.updatedDataList',this.updatedDataList); // 这将打印出更新后的整个数据对象，其中只包含 selectValue 中指定的版本
    },

    surebtn() {
      console.log("checkModels", this.checkModels);
      this.$emit("infoModel", this.checkModels);
      this.showSelectDialog = false;
      this.$emit("onClose", false);
      this.checkModels = JSON.parse(JSON.stringify(this.checkModels));
      this.$forceUpdate();
    },

    currentSelect(data) {
      // 直接更新显示状态
      if (data.checked) {
        let index = this.checkModels.findIndex((o) => o.model_id === data.id);
        console.log("index", index);
        if (index < 0) {
          // let index = data.versions.findIndex(
          //   (o) => o.id === data.model_version_id
          // );
          // data.model_version = data.versions[index];
          console.log("data", this.updatedDataList);
          this.checkModels.push(...this.updatedDataList);
          console.log("this.checkModels", this.checkModels);
        }
      } else {
        let index = -1;
        index = this.checkModels.findIndex((o) => o.model_id === data.id);
        if (index > -1) {
          this.checkModels.splice(index, 1);
        }
      }
      this.$forceUpdate();
    },
    async getModels() {
      let res = await getModelsWithVersion({
        ...this.Pagedata,
        visibility: this.visibility,
      });
      this.Pagedata.total = res.data.total;
      let data = res.data.list;
      for (let item of data) {
        item.checked = false;
        item.model_id = item.id;
        let model = {
          name: item.name,
          alias: item.alias,
        };
        item.model = model;
        //判断是否选中
        for (let checkItem of this.checkModels) {
          if (checkItem.model_id == item.id) {
            item.checked = true;
            item.model_version_id = checkItem.model_version_id;
            item.model_version = checkItem.model_version;
            console.log(
              "checkItem.model_version",
              checkItem.model_version.version
            );
          }
        }
        if (!item.checked) {
          item.model_version_id = item.versions[0].id;
          item.model_version = item.versions[0];
        }
      }
      this.tableData = data;
      this.$forceUpdate();
    },
    // versionSelect(data) {
    //   console.log("data", data);
    //   let index = data.versions.findIndex(
    //     (o) => o.id === data.model_version_id
    //   );
    //   data.model_version = data.versions[index];
    //   index = this.checkModels.findIndex(
    //     (o) => o.model_id.toString() === data.id.toString()
    //   );
    //   console.log("index", index);
    //   if (index >= 0) {
    //     this.checkModels[index].model_version_id = data.model_version_id;
    //     this.checkModels[index].model_version = data.model_version;
    //     console.log("id", this.checkModels[index].model_version.id);
    //     console.log("model_id", this.checkModels[index].model_version_id);
    //     console.log("model_id", this.checkModels[index].model_version.version);
    //   }
    //   this.$forceUpdate();
    // },
    selectName() {
      debounce(() => {
        this.getModels();
      }, 400)();
    },
    enter() {
      this.getModels();
    },
    tabClick() {
      this.Pagedata.current = 1;
      this.getModels();
    },
    handleCurrentChange(val) {
      this.Pagedata.current = val;
      this.getModels();
    },
    removetag(index) {
      this.checkModels.splice(index, 1);
      this.checkModels = JSON.parse(JSON.stringify(this.checkModels));
      console.log(this.checkModels);
      this.$emit("infoModel", this.checkModels);
    },
    onClose() {
      this.showSelectDialog = false;
      this.$emit("onClose", false);
    },
    initCheckModel() {
      for (let data of this.checkModels) {
        data.model_version_id = Number(data.model_version_id);
      }
    },

    // setCheckOn(data) {
    //   for (let item of data) {
    //     if (item.latest_versions.length > 0) {
    //       item.version = item.latest_versions[0]
    //     }
    //     console.log("checkModels", this.checkModels)
    //     for (let data of this.checkModels) {
    //       if (data.id == item.id) {
    //         item.checked = true
    //         item.version = data.version
    //         console.log('item', item)
    //         break
    //       }
    //       else {
    //         item.checked = false
    //         console.log('true')
    //       }
    //     }
    //   }
    // },

    showSelectBox() {
      this.showSelectDialog = true;
      this.getModels();
    },
  },
  components: {
    DialogBox,
  },
  mounted() {
    // console.log('aa', this.dataset_list)

    // console.log('bb')
    this.getModels();
    this.checkModels = JSON.parse(JSON.stringify(this.model_list));
    this.initCheckModel();
    console.log("cc");
  },
  destroyed() {},
};
</script>

<style lang="less" scoped>
@import "~@/assets/css/task.less";
.myself-dataset-checkbox {
  display: flex;

  /deep/ .el-checkbox__input {
    padding-top: 28px;
  }
}

.infinite-list {
  min-height: 380px;
  padding: 20px 0;
}

//.infinite-list-item {
//  margin-bottom: 20px;
//  float: left;
//  //width: 496px;
//  width: 992px; //数据集改版后调整为一行一个
//}

.infinite-list-item {
  //margin-bottom: 20px;
  //float: left;
  ////width: 496px;
  //width: 992px; //数据集改版后调整为一行一个
  width: 100%;
  //background: white;
  margin-bottom: 12px;
  padding: 10px 18px;
  //background: #4AE287;
}

.elrowgutter {
  /deep/.el-button--default {
    margin-left: 100px;
    width: 80%;
    background-color: #f5f7fa;
    color: #1e2480;
    margin-bottom: 20px;
  }

  /deep/.el-form-item__label {
    text-align: right;
    padding-right: 30px;
  }
}

.delnode {
  margin-left: 73%;
}

.run-model-title {
  color: #303133;
}

.run-model-table {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 0 8px;
  margin-top: 6px;

  .r-m-box {
    border-top: 1px solid #e8e8e8;
    height: 38px;
    line-height: 38px;

    .r-m-name {
      float: left;
      width: 148px;
      padding-left: 14px;
    }

    .r-m-product {
      float: left;
      width: 250px;
    }

    .r-m-command {
      float: left;
      width: 120px;

      .popover {
        cursor: pointer;

        i {
          font-size: 16px;
          color: #4285f4;
        }
      }
    }

    .r-m-number {
      float: left;
    }
  }

  .no-border {
    border: 0;
  }
}

.el-tooltip__popper {
  max-width: 400px;
  line-height: 180%;
}

.checkbox-true {
  // background: url(~@/assets/img/checkbox-true.jpg) no-repeat;
  background-size: 18px 18px;
}

.checkbox-false {
  // background: url(~@/assets/img/checkbox-false.jpg) no-repeat;
  background-size: 18px 18px;
}

.adorn-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  float: left;
  margin-top: 20px;
  margin-right: 10px;
}

.dimg {
  width: 123px;
  height: 75px;
  float: left;
}

.datas-box {
  float: left;
  // width: 296px;

  .datasname {
    vertical-align: top;
    font-weight: 800;
    font-size: 16px;
    line-height: 22px;
    overflow: hidden;
    display: -webkit-box; //将元素设为盒子伸缩模型显示
    -webkit-box-orient: vertical; //伸缩方向设为垂直方向
    -webkit-line-clamp: 1;
  }

  .pcontents {
    margin: 15px 0 0 5px;
    font-size: 14px;
    color: #606266;
    line-height: 24px;
    margin-top: 5px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .pall {
    overflow: hidden;
    margin-left: 5px;
  }
}

.version-box {
  float: right;

  .sb {
    /deep/.el-input.el-input__inner {
      border-color: #4285f4 !important;
      font-size: 12;
    }
  }
}

.dataset-tags-box {
  // width: 240px;
  margin-bottom: 10px;
  position: relative;
  overflow: hidden;

  .dataset-addr {
    padding-left: 10px;
    line-height: 30px;
    float: left;
  }

  .delstr {
    color: red;
  }
}

.dataset-tags {
  // display: block;
  // max-width: 240px;
  float: left;

  /deep/ .el-tag__close {
    float: left;
    margin-top: 6px;
  }

  .dataset-tags-word {
    // display: inline-block;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    width: 140px;
    float: left;
  }
}

.pall-title {
  overflow: hidden;

  .datasname {
    float: left;
    line-height: 28px;
  }

  .pall-versions {
    float: left;
    margin-left: 10px;

    span {
      margin-right: 4px;
      font-size: 12px;
    }
  }
}

//暂时更改
/deep/ .el-button--default {
  background: #333b54;
  border-color: #4a567e;
  color: #b8c2e5 !important;
}

.radio_box {
  margin-top: 20px;
}

/deep/ .el-input__inner {
  background: #465072;
  border: 1px solid #8492c2;
  color: white !important;
}

/deep/ .el-dialog {
  background: #1a1e2c;
}

/deep/ .datas-box .pcontents {
  color: #8492c2;
}

.infinite-list-item:hover {
  background: #343e5f;
}

.clearfix {
  background: #252c44;
}

/deep/ .el-pagination.is-background .el-pager li {
  background: #202432;
}

/deep/ .pagination-box .btn-prev,
/deep/ .pagination-box .btn-next {
  border: 1px solid #177ddc;
  background: #202432;
}
.radio_box {
  margin-top: 20px;
}
</style>
